package cn.summit.config;

import cn.summit.entity.Perm;
import cn.summit.service.PermService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 初始化url权限
 *
 * @author summit
 * @since 2020/2/13 16:28
 */
@Service("urlAuthServiceImpl")
@Slf4j
public class UrlAuthServiceImpl implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermService permService;

    private volatile HashMap<String, Collection<ConfigAttribute>> map = null;

    private void loadAllUrlAuthPerm() {
        log.debug("初始化权限map。。。。。。。。。。。。");
        List<Perm> list = permService.list();

        map = new HashMap<>();
        Collection<ConfigAttribute> array;
        ConfigAttribute cfg;
        for (Perm permission : list) {
            array = new ArrayList<>();
            cfg = new SecurityConfig(permission.getAuth());
            //此处只添加了用户的名字，其实还可以添加更多权限的信息，例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
            array.add(cfg);
            //用权限的getUrl() 作为map的key，用ConfigAttribute的集合作为 value，
            map.put(permission.getUrl(), array);
        }

    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if (map == null) {
            loadAllUrlAuthPerm();
        }
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        log.info("url权限拦截,ip[{}]",request.getRemoteAddr());
        log.info("当前访问url" + request.getRequestURL());
        AntPathRequestMatcher matcher;
        String resUrl;
        for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
            resUrl = iter.next();
            matcher = new AntPathRequestMatcher(resUrl);
            if (matcher.matches(request)) {
                log.info("当前用户访问url[{}],auth[{}]", request.getRequestURI(), map.get(resUrl));
                return map.get(resUrl);
            }
        }
        log.debug("当前url[{}]未配置权限控制",request.getRequestURI());
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
